import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

/**
 * Created with IntelliJ IDEA.
 * Description:非递归前、中、后序遍历
 * Date: 2024-02-07
 * Time:13:46
 */
public class Solution {
    Stack<TreeNode> stack = new Stack<>();
    public List<Integer> preorderTraversal(TreeNode root) {
        if(root == null)
            return new ArrayList<>();

        List<Integer> list = new ArrayList<>();
        stack.push(root);
        TreeNode cur = root;
        while(!stack.isEmpty()) {
            TreeNode top = stack.pop();
            list.add(top.val);
            if(top.right != null)
                stack.push(top.right);
            if(top.left != null)
                stack.push(top.left);
        }
        return list;
    }

    public List<Integer> preorderNorR(TreeNode root) {
        if(root == null)
            return new ArrayList<>();
        List<Integer> list = new ArrayList<>();
        TreeNode cur = root;
        while(cur != null || !stack.isEmpty()) {
            while(cur != null) {
                list.add(cur.val);
                stack.push(cur);
                cur = cur.left;
            }
            TreeNode top = stack.pop();
            cur = top.right;
        }
        return list;
    }
///////////////////////////////////////////////////////////////
    public List<Integer> inorderNorR(TreeNode root) {
        if(root == null)
            return null;
        List<Integer> list = new ArrayList<>();
        TreeNode cur = root;
        while(cur != null || !stack.isEmpty()) {
            while(cur != null) {  //不为空就把遍历到每个节点入栈
                stack.push(cur);
                cur = cur.left;
            }
            TreeNode top = stack.pop(); //到这里说明左子树遍历完了
            list.add(top.val);
            cur = top.right;
        }
        return list;
    }
///////////////////////////////////////////////////////////////
    public List<Integer> postorderNorR(TreeNode root) {
        if(root == null)
            return new ArrayList<>();
        List<Integer> list = new ArrayList<>();
        TreeNode cur = root;
        TreeNode prev =null;  //标记上一个访问的节点
        while(cur != null || !stack.isEmpty()) {
            while(cur != null) {
                stack.push(cur);
                cur = cur.left;
            }
            TreeNode top = stack.peek(); //到这里说明左子树遍历完了
            if(top.right == null || prev == top.right) { //右子树为空或者右子树已经访问过了，那就把当前的根节点出栈
                list.add(top.val);
                prev = top;
                stack.pop();
            } else {
                cur = top.right;
            }

        }
        return list;
    }

}
